<template>
	<view class="tab-page">
		<nav-bar search @search="onSearch()">消息</nav-bar>
		<view v-if="loading" class="chat-loading">
			<loading :size="50" :mask="false">
				<view>消息接收中...</view>
			</loading>
		</view>
		<view v-if="initializing" class="chat-loading">
			<loading :size="50" :mask="false">
				<view>正在初始化...</view>
			</loading>
		</view>
		<view class="nav-bar" v-if="showSearch">
			<view class="nav-search">
				<uni-search-bar focus="true" radius="100" v-model="searchText" cancelButton="none"
					placeholder="搜索"></uni-search-bar>
			</view>
		</view>
		<view class="chat-tip" v-if="!loading && chatStore.chats.length == 0">
			温馨提示：您现在还没有任何聊天消息，快跟您的好友发起聊天吧~
		</view>
		<scroll-view class="scroll-bar" v-else scroll-with-animation="true" scroll-y="true">
			<view v-for="(chat, index) in chatStore.chats" :key="index">
				<long-press-menu v-if="isShowChat(chat)" :items="menu.items" @select="onSelectMenu($event, index)">
					<chat-item :chat="chat" :index="index" :active="menu.chatIdx == index"></chat-item>
				</long-press-menu>
			</view>
		</scroll-view>
		<popup-modal ref="modal"></popup-modal>
	</view>
</template>

<script>
import useChatStore from '@/store/chatStore.js'

export default {
	data() {
		return {
			showSearch: false,
			searchText: "",
			menu: {
				show: false,
				style: "",
				chatIdx: -1,
				isTouchMove: false,
				items: [{
					key: 'DELETE',
					name: '删除该聊天',
					icon: 'trash',
					color: '#e64e4e'
				},
				{
					key: 'TOP',
					name: '置顶该聊天',
					icon: 'arrow-up'
				}
				]
			}
		}
	},
	methods: {
		onSelectMenu(item, chatIdx) {
			switch (item.key) {
				case 'DELETE':
					this.removeChat(chatIdx);
					break;
				case 'TOP':
					this.moveToTop(chatIdx);
					break;
				default:
					break;
			}
			this.menu.show = false;
		},
		removeChat(chatIdx) {
			this.chatStore.removeChat(chatIdx);
		},
		moveToTop(chatIdx) {
			this.chatStore.moveTop(chatIdx);
		},
		isShowChat(chat) {
			if (chat.delete) {
				return false;
			}
			return !this.searchText || chat.showName.includes(this.searchText)
		},
		onSearch() {
			this.showSearch = !this.showSearch;
			this.searchText = "";
		},
		refreshUnreadBadge() {
			if (this.unreadCount > 0) {
				uni.setTabBarBadge({
					index: 0,
					text: this.unreadCount + ""
				})
			} else {
				uni.removeTabBarBadge({
					index: 0,
					complete: () => {}
				})
			}
			// Android平台调用原生API设置角标
			// #ifdef APP-PLUS
			if (uni.getSystemInfoSync().platform === 'android') {
				plus.runtime.setBadgeNumber(this.unreadCount);
			}
			// #endif
		},
		checkNotifyPermisson() {
			// #ifdef APP-PLUS  
			if (plus.os.name == 'Android') { // 判断是Android
				var main = plus.android.runtimeMainActivity();
				var pkName = main.getPackageName();
				var uid = main.getApplicationInfo().plusGetAttribute("uid");
				var NotificationManagerCompat = plus.android.importClass(
					"android.support.v4.app.NotificationManagerCompat");
				//android.support.v4升级为androidx
				if (NotificationManagerCompat == null) {
					NotificationManagerCompat = plus.android.importClass("androidx.core.app.NotificationManagerCompat");
				} 
				var areNotificationsEnabled = NotificationManagerCompat.from(main).areNotificationsEnabled();
				// 未开通‘允许通知’权限，则弹窗提醒开通，并点击确认后，跳转到系统设置页面进行设置  
				if (!areNotificationsEnabled) {
					this.$refs.modal.open({
						title: '系统消息',
						content: '您还没有开启通知权限，无法接受到消息通知！',
						confirmText: '去设置',
						success: () => {
							var Intent = plus.android.importClass('android.content.Intent');
							var Build = plus.android.importClass("android.os.Build");
							//android 8.0引导  
							if (Build.VERSION.SDK_INT >= 26) {
								var intent = new Intent('android.settings.APP_NOTIFICATION_SETTINGS');
								intent.putExtra('android.provider.extra.APP_PACKAGE', pkName);
							} else if (Build.VERSION.SDK_INT >= 21) { //android 5.0-7.0  
								var intent = new Intent('android.settings.APP_NOTIFICATION_SETTINGS');
								intent.putExtra("app_package", pkName);
								intent.putExtra("app_uid", uid);
							} else { //(<21)其他--跳转到该应用管理的详情页  
								var Settings = plus.android.importClass("android.provider.Settings");''
								intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
								var uri = Uri.fromParts("package", mainActivity.getPackageName(), null);
								intent.setData(uri);
							}
							// 跳转到该应用的系统通知设置页  
							main.startActivity(intent);
							
						}
					});
				}
			} else if (plus.os.name == 'iOS') { // 判断是ISO
				var isOn = undefined;
				var types = 0;
				var app = plus.ios.invoke('UIApplication', 'sharedApplication');
				var settings = plus.ios.invoke(app, 'currentUserNotificationSettings');
				if (settings) {
					types = settings.plusGetAttribute('types');
					plus.ios.deleteObject(settings);
				} else {
					types = plus.ios.invoke(app, 'enabledRemoteNotificationTypes');
				}
				plus.ios.deleteObject(app);
				isOn = (0 != types);
				if (isOn == false) {
					this.$refs.modal.open({
						title: '系统消息',
						content: '您还没有开启通知权限，无法接受到消息通知！',
						confirmText: '去设置',
						success: ()=> {
							var app = plus.ios.invoke('UIApplication', 'sharedApplication');
							var setting = plus.ios.invoke('NSURL', 'URLWithString:', 'app-settings:');
							plus.ios.invoke(app, 'openURL:', setting);
							plus.ios.deleteObject(setting);
							plus.ios.deleteObject(app);
						}
					});
				}
			}
			// #endif  
		}
	},
	computed: {
		unreadCount() {
			let count = 0;
			this.chatStore.chats.forEach(chat => {
				if (!chat.delete) {
					count += chat.unreadCount;
				}
			})
			return count;
		},
		loading() {
			return this.chatStore.isLoading();
		},
		initializing(){
			return !getApp().$vm.isInit;
		}
	},
	watch: {
		unreadCount(newCount, oldCount) {
			this.refreshUnreadBadge();
		}
	},
	onLoad() {
		// 检查通知权限
		setTimeout(() => this.checkNotifyPermisson(), 1000)
	},
	onShow() {
		this.refreshUnreadBadge();
	}
}
</script>

<style  lang="scss">
.tab-page {
	position: relative;
	display: flex;
	flex-direction: column;

	.chat-tip {
		position: absolute;
		top: 400rpx;
		padding: 50rpx;
		line-height: 50rpx;
		text-align: center;
		color: $im-text-color-lighter;
	}
	
	.chat-loading {
		display: block;
		width: 100%;
		height: 120rpx;
		background: white;

		color: $im-text-color-lighter;

		.loading-box {
			position: relative;
		}
	}

	.scroll-bar {
		flex: 1;
		height: 100%;
	}
}
</style>